<template>
  <div class="announcement">
    
    <!-- 搜索栏 -->
    <el-card class="search-card">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="关键词">
          <el-input v-model="searchForm.keyword" placeholder="请输入公告标题或内容关键词" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 150px;">
            <el-option label="全部" value="" />
            <el-option label="草稿" value="draft" />
            <el-option label="已发布" value="published" />
            <el-option label="定时发布" value="scheduled" />
          </el-select>
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="searchForm.category" placeholder="请选择分类" style="width: 150px;">
            <el-option label="全部" value="" />
            <el-option label="系统公告" value="系统公告" />
            <el-option label="产品公告" value="产品公告" />
            <el-option label="活动公告" value="活动公告" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    
    <!-- 操作按钮 -->
    <el-card class="action-card">
      <el-button type="primary" @click="handleCreate">
        <el-icon><Plus /></el-icon>
        新增公告
      </el-button>
    </el-card>
    
    <!-- 公告列表 -->
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <span>公告列表</span>
          <el-button type="primary" @click="handleRefresh">刷新</el-button>
        </div>
      </template>
      
      <el-table :data="tableData" style="width: 100%" v-loading="loading">
        <el-table-column prop="title" label="公告标题" min-width="20%">
          <template #default="scope">
            <span class="clickable-title" @click="handleViewDetail(scope.row)">
              {{ scope.row.title }}
            </span>
          </template>
        </el-table-column>
        <el-table-column prop="category" label="分类" min-width="15%" />
        <el-table-column prop="publishTime" label="发布时间" min-width="15%" />
        <el-table-column prop="status" label="状态" min-width="15%">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">
              {{ scope.row.statusDisplay || getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="isTop" label="置顶" min-width="10%">
          <template #default="scope">
            <el-tag v-if="scope.row.isTop" type="warning" size="small">置顶</el-tag>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" min-width="25%">
          <template #default="scope">
            <el-button type="info" size="small" @click="handlePreview(scope.row)">
              预览
            </el-button>
            <el-button type="primary" size="small" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button 
              v-if="scope.row.status === 'draft'"
              type="success" 
              size="small" 
              @click="handleToggleStatus(scope.row, 'published')"
            >
              发布
            </el-button>
            <el-button 
              v-if="scope.row.status === 'published'"
              type="warning" 
              size="small" 
              @click="handleToggleStatus(scope.row, 'draft')"
            >
              取消发布
            </el-button>
            <el-button 
              v-if="!scope.row.isTop"
              type="warning" 
              size="small" 
              @click="handleToggleTop(scope.row, true)"
            >
              置顶
            </el-button>
            <el-button 
              v-if="scope.row.isTop"
              type="info" 
              size="small" 
              @click="handleToggleTop(scope.row, false)"
            >
              取消置顶
            </el-button>
            <el-button 
              type="danger" 
              size="small" 
              @click="handleDelete(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="editDialogVisible"
      :title="isEdit ? '编辑公告' : '新增公告'"
      width="80%"
    >
      <el-form :model="editForm" label-width="100px" v-if="editForm">
        <el-form-item label="公告标题" required>
          <el-input v-model="editForm.title" placeholder="请输入公告标题" />
        </el-form-item>
        <el-form-item label="分类">
          <el-select v-model="editForm.category" placeholder="请选择分类" style="width: 100%;">
            <el-option label="系统公告" value="系统公告" />
            <el-option label="产品公告" value="产品公告" />
            <el-option label="活动公告" value="活动公告" />
            <el-option label="其他" value="其他" />
          </el-select>
        </el-form-item>
        <el-form-item label="置顶">
          <el-switch v-model="editForm.isTop" />
        </el-form-item>
        <el-form-item label="定时发布">
          <el-switch v-model="editForm.scheduled" />
          <el-date-picker
            v-if="editForm.scheduled"
            v-model="editForm.scheduleTime"
            type="datetime"
            placeholder="选择发布时间"
            style="margin-left: 10px; width: 200px;"
          />
        </el-form-item>
        <el-form-item label="公告内容" required>
          <SimpleRichEditor
            v-model="editForm.content"
            placeholder="请输入公告内容"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button @click="handleSaveDraft">保存草稿</el-button>
          <el-button type="primary" @click="handleSave">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="公告详情"
      width="70%"
    >
      <div v-if="currentDetail" class="preview-content">
        <h2>{{ currentDetail.title }}</h2>
        <div class="preview-meta">
          <div class="meta-row">
            <span><strong>分类：</strong>{{ currentDetail.category }}</span>
            <span><strong>状态：</strong>{{ currentDetail.statusDisplay }}</span>
            <span><strong>作者：</strong>{{ currentDetail.authorName }}</span>
          </div>
          <div class="meta-row">
            <span><strong>发布时间：</strong>{{ currentDetail.publishTime || '未发布' }}</span>
            <span><strong>定时发布时间：</strong>{{ currentDetail.scheduledPublishTime || '无' }}</span>
            <span><strong>最后修改：</strong>{{ currentDetail.lastModifiedTime }}</span>
          </div>
          <div class="meta-row">
            <span><strong>置顶状态：</strong>
              <el-tag v-if="currentDetail.isTop" type="warning" size="small">置顶</el-tag>
              <span v-else>普通</span>
            </span>
          </div>
        </div>
        <div class="preview-body" v-html="currentDetail.content"></div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getAnnouncementList, getAnnouncementDetail, createAnnouncement, updateAnnouncement, deleteAnnouncement, toggleTopAnnouncement, updateAnnouncementStatus } from '@/api/announcement'
import SimpleRichEditor from '@/components/SimpleRichEditor.vue'

const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const editDialogVisible = ref(false)
const previewDialogVisible = ref(false)
const currentDetail = ref(null)
const editForm = ref(null)
const isEdit = ref(false)

const searchForm = reactive({
  keyword: '',
  status: '',
  category: ''
})

const tableData = ref([])

// 获取公告列表
const fetchAnnouncementList = async () => {
  loading.value = true
  try {
    const params = {
      page: currentPage.value,
      size: pageSize.value
    }
    
    // 添加搜索条件
    if (searchForm.keyword) {
      params.keyword = searchForm.keyword
    }
    if (searchForm.status) {
      params.status = searchForm.status
    }
    if (searchForm.category) {
      params.category = searchForm.category
    }
    
    const response = await getAnnouncementList(params)
    
    if (response.code === 200) {
      tableData.value = response.data.articles.map(article => ({
        ...article,
        publishTime: article.publishTime ? formatDateTime(article.publishTime) : null,
        scheduledPublishTime: article.scheduledPublishTime ? formatDateTime(article.scheduledPublishTime) : null,
        lastModifiedTime: article.lastModifiedTime ? formatDateTime(article.lastModifiedTime) : null
      }))
      total.value = response.data.total
    } else {
      ElMessage.error(response.message || '获取公告列表失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '获取公告列表失败')
  } finally {
    loading.value = false
  }
}

// 格式化日期时间
const formatDateTime = (dateTimeStr) => {
  if (!dateTimeStr) return ''
  const date = new Date(dateTimeStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  })
}

const getPublishTypeTag = (type) => {
  const typeMap = {
    normal: 'info',
    important: 'warning',
    urgent: 'danger'
  }
  return typeMap[type] || 'info'
}

const getPublishTypeText = (type) => {
  const typeMap = {
    normal: '普通公告',
    important: '重要公告',
    urgent: '紧急公告'
  }
  return typeMap[type] || '未知'
}

const getStatusType = (status) => {
  const statusMap = {
    draft: 'info',
    published: 'success',
    scheduled: 'warning'
  }
  return statusMap[status] || 'info'
}

const getStatusText = (status) => {
  const statusMap = {
    draft: '草稿',
    published: '已发布',
    scheduled: '定时发布'
  }
  return statusMap[status] || '未知'
}

const handleCreate = () => {
  isEdit.value = false
  editForm.value = {
    title: '',
    category: '系统公告',
    isTop: false,
    scheduled: false,
    scheduleTime: null,
    content: ''
  }
  editDialogVisible.value = true
}

const handleEdit = async (row) => {
  try {
    const response = await getAnnouncementDetail(row.articleId)
    if (response.code === 200) {
      isEdit.value = true
      editForm.value = {
        articleId: response.data.articleId,
        title: response.data.title,
        content: response.data.content,
        category: response.data.category,
        status: response.data.status,
        isTop: response.data.isTop,
        scheduled: response.data.scheduledPublishTime !== null,
        scheduleTime: response.data.scheduledPublishTime ? new Date(response.data.scheduledPublishTime) : null
      }
      editDialogVisible.value = true
    } else {
      ElMessage.error(response.message || '获取公告详情失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '获取公告详情失败')
  }
}

const handleViewDetail = async (row) => {
  try {
    const response = await getAnnouncementDetail(row.articleId)
    if (response.code === 200) {
      currentDetail.value = {
        ...response.data,
        publishTime: response.data.publishTime ? formatDateTime(response.data.publishTime) : null,
        scheduledPublishTime: response.data.scheduledPublishTime ? formatDateTime(response.data.scheduledPublishTime) : null,
        lastModifiedTime: response.data.lastModifiedTime ? formatDateTime(response.data.lastModifiedTime) : null
      }
      previewDialogVisible.value = true
    } else {
      ElMessage.error(response.message || '获取公告详情失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '获取公告详情失败')
  }
}

const handlePreview = async (row) => {
  try {
    const response = await getAnnouncementDetail(row.articleId)
    if (response.code === 200) {
      currentDetail.value = {
        ...response.data,
        publishTime: response.data.publishTime ? formatDateTime(response.data.publishTime) : null,
        scheduledPublishTime: response.data.scheduledPublishTime ? formatDateTime(response.data.scheduledPublishTime) : null,
        lastModifiedTime: response.data.lastModifiedTime ? formatDateTime(response.data.lastModifiedTime) : null
      }
      previewDialogVisible.value = true
    } else {
      ElMessage.error(response.message || '获取公告详情失败')
    }
  } catch (error) {
    ElMessage.error(error.message || '获取公告详情失败')
  }
}



const handleDelete = async (row) => {
  ElMessageBox.confirm(
    '确定要删除该公告吗？删除后无法恢复。',
    '确认删除',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await deleteAnnouncement(row.articleId)
      
      if (response.code === 200) {
        ElMessage.success('公告删除成功')
        // 刷新列表
        fetchAnnouncementList()
      } else {
        ElMessage.error(response.message || '删除公告失败')
      }
    } catch (error) {
      ElMessage.error(error.message || '删除公告失败')
    }
  }).catch(() => {
    // 用户取消删除，不做任何操作
  })
}

const handleToggleTop = async (row, isTop) => {
  const action = isTop ? '置顶' : '取消置顶'
  
  ElMessageBox.confirm(
    `确定要${action}该公告吗？`,
    `确认${action}`,
    {
      confirmButtonText: `确定${action}`,
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await toggleTopAnnouncement(row.articleId, isTop)
      
      if (response.code === 200) {
        ElMessage.success(`公告${action}成功`)
        // 刷新列表
        fetchAnnouncementList()
      } else if (response.code === 400) {
        ElMessage.warning(response.message || '只有已发布的公告才能置顶')
      } else {
        ElMessage.error(response.message || `${action}公告失败`)
      }
    } catch (error) {
      // 处理500错误或其他网络错误
      if (error.response && error.response.status === 500) {
        ElMessage.warning('只有已发布的公告才能置顶')
      } else {
        ElMessage.error(error.message || `${action}公告失败`)
      }
    }
  }).catch(() => {
    // 用户取消操作，不做任何操作
  })
}

const handleToggleStatus = async (row, newStatus) => {
  const action = newStatus === 'published' ? '发布' : '取消发布'
  
  ElMessageBox.confirm(
    `确定要${action}该公告吗？`,
    `确认${action}`,
    {
      confirmButtonText: `确定${action}`,
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const response = await updateAnnouncementStatus(row.articleId, newStatus)
      
      if (response.code === 200) {
        ElMessage.success(`公告${action}成功`)
        // 刷新列表
        fetchAnnouncementList()
      } else {
        ElMessage.error(response.message || `${action}公告失败`)
      }
    } catch (error) {
      ElMessage.error(error.message || `${action}公告失败`)
    }
  }).catch(() => {
    // 用户取消操作，不做任何操作
  })
}

const handleSaveDraft = async () => {
  if (!editForm.value.title.trim()) {
    ElMessage.warning('请输入公告标题')
    return
  }
  
  try {
    const data = {
      title: editForm.value.title.trim(),
      content: editForm.value.content.trim() || '<p>草稿内容</p>',
      category: editForm.value.category,
      status: 'draft',
      isTop: editForm.value.isTop,
      scheduledPublishTime: null
    }
    
    let response
    if (isEdit.value) {
      // 编辑模式
      response = await updateAnnouncement(editForm.value.articleId, data)
      if (response.code === 200) {
        ElMessage.success('草稿已保存')
      } else {
        ElMessage.error(response.message || '保存草稿失败')
        return
      }
    } else {
      // 创建模式
      response = await createAnnouncement(data)
      if (response.code === 200) {
        ElMessage.success('草稿已保存')
      } else {
        ElMessage.error(response.message || '保存草稿失败')
        return
      }
    }
    
    editDialogVisible.value = false
    // 刷新列表
    fetchAnnouncementList()
  } catch (error) {
    ElMessage.error(error.message || '保存草稿失败')
  }
}

const handleSave = async () => {
  if (!editForm.value.title.trim()) {
    ElMessage.warning('请输入公告标题')
    return
  }
  
  if (!editForm.value.content.trim()) {
    ElMessage.warning('请输入公告内容')
    return
  }
  
  try {
    const data = {
      title: editForm.value.title.trim(),
      content: editForm.value.content.trim(),
      category: editForm.value.category,
      status: editForm.value.scheduled && editForm.value.scheduleTime ? 'scheduled' : 'published',
      isTop: editForm.value.isTop,
      scheduledPublishTime: editForm.value.scheduled && editForm.value.scheduleTime ? 
        editForm.value.scheduleTime.toISOString() : null
    }
    
    let response
    if (isEdit.value) {
      // 编辑模式 - 保持原有状态，但处理定时发布
      const editData = {
        ...data,
        status: editForm.value.scheduled && editForm.value.scheduleTime ? 'scheduled' : editForm.value.status
      }
      response = await updateAnnouncement(editForm.value.articleId, editData)
      if (response.code === 200) {
        ElMessage.success('公告编辑成功')
      } else {
        ElMessage.error(response.message || '编辑公告失败')
        return
      }
    } else {
      // 创建模式
      response = await createAnnouncement(data)
      if (response.code === 200) {
        ElMessage.success('公告创建成功')
      } else {
        ElMessage.error(response.message || '创建公告失败')
        return
      }
    }
    
    editDialogVisible.value = false
    // 刷新列表
    fetchAnnouncementList()
  } catch (error) {
    ElMessage.error(error.message || (isEdit.value ? '编辑公告失败' : '创建公告失败'))
  }
}

const handleSearch = () => {
  currentPage.value = 1
  fetchAnnouncementList()
}

const handleReset = () => {
  searchForm.keyword = ''
  searchForm.status = ''
  searchForm.category = ''
  currentPage.value = 1
  fetchAnnouncementList()
}

const handleRefresh = () => {
  fetchAnnouncementList()
}



const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchAnnouncementList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchAnnouncementList()
}

onMounted(() => {
  // 初始化数据
  fetchAnnouncementList()
})
</script>

<style scoped>
.announcement {
  padding: 0;
  width: 100%;
  min-height: 100%;
  box-sizing: border-box;
}

.announcement h2 {
  margin-bottom: 20px;
  color: #333;
}

.search-card {
  margin-bottom: 20px;
  width: 100%;
  box-sizing: border-box;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
  align-items: center;
}

.search-form .el-form-item {
  margin-bottom: 0;
  margin-right: 0;
}

.action-card {
  margin-bottom: 20px;
  width: 100%;
}

.table-card {
  margin-bottom: 20px;
  width: 100%;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  text-align: right;
}



.preview-content {
  padding: 20px;
}

.preview-content h2 {
  margin-bottom: 20px;
  color: #333;
  text-align: center;
}

.preview-meta {
  margin-bottom: 20px;
  padding: 15px;
  background-color: #f5f7fa;
  border-radius: 4px;
  color: #666;
  font-size: 14px;
}

.meta-row {
  display: flex;
  gap: 30px;
  margin-bottom: 8px;
}

.meta-row:last-child {
  margin-bottom: 0;
}

.meta-row span {
  min-width: 120px;
}

.clickable-title {
  color: #409EFF;
  cursor: pointer;
  text-decoration: none;
  transition: color 0.3s;
}

.clickable-title:hover {
  color: #66b1ff;
  text-decoration: underline;
}

.preview-body {
  line-height: 1.8;
  color: #333;
}

.preview-body p {
  margin-bottom: 10px;
}

.preview-body ul {
  margin-bottom: 10px;
  padding-left: 20px;
}

.preview-body li {
  margin-bottom: 5px;
}

/* 表格样式优化 */
:deep(.el-table) {
  width: 100% !important;
  font-size: 14px;
}

:deep(.el-table th) {
  background-color: #fafafa;
  font-weight: 600;
  color: #333;
}

:deep(.el-table td) {
  padding: 12px 0;
}

:deep(.el-table .cell) {
  padding: 0 12px;
}

/* 表格列宽度优化 */
:deep(.el-table .el-table__column) {
  min-width: 120px;
}
</style> 